import React, { useEffect, useState } from 'react';
import { Modal, Icon, Result } from 'antd';
import { ReactSortable } from 'react-sortablejs';
import styles from './index.less';

/**
 * 可排序表格
 * @param {Boolean} visible 是否显示弹窗
 * @param {String} fieldName 需要展示的字段名
 * @param {Function} onChange 点击OK后的回调
 * @param {Function} onCancel 点击Cancel后的回调
 * @param {Array} dataSource 数据源
 */
const SortableModal = ({ title = '自定义表头', visible, fieldName = 'title', onChange, onCancel, dataSource = [] }) => {
    const [selectedData, setSelectedData] = useState([]);
    const [unselectedData, setUnselectedData] = useState([]);

    // 根据数据源拆分为已显示项和未显示项
    useEffect(() => {
        if (dataSource.length) {
            const selected = dataSource.filter(i => i.isSelected === true);
            const unselected = dataSource.filter(i => !i.isSelected);

            setSelectedData(selected);
            setUnselectedData(unselected);
        }
    }, [visible, dataSource]);

    // 删除
    const handleRemove = value => {
        setSelectedData(state => state.filter(item => item[fieldName] !== value[fieldName]));
        setUnselectedData(state => [...state, { ...value, isSelected: false }]);
    };

    // 添加
    const handleAdd = value => {
        setUnselectedData(state => state.filter(item => item[fieldName] !== value[fieldName]));
        setSelectedData(state => [...state, { ...value, isSelected: true }]);
    };

    // 点击OK
    const handleModalOk = () => {
        if (onChange) {
            const result = [...selectedData, ...unselectedData];
            onChange(selectedData, result);
        }
    };

    // 点击取消
    const handleModalCancel = () => {
        if (onCancel) {
            onCancel();
        }
    };

    // 禁止拖拽已禁用的选项
    const handleSortMove = e =>
        e.dragged.getAttribute('data-disabled') !== 'true' && e.related.getAttribute('data-disabled') !== 'true';

    return (
        <Modal
            title={title}
            width={880}
            closable={false}
            visible={visible}
            className={styles.sortableModal}
            okButtonProps={{ disabled: !dataSource.length }}
            onOk={handleModalOk}
            onCancel={handleModalCancel}
        >
            {dataSource.length ? (
                <>
                    <div className={styles.selectedWrapper}>
                        <p>已显示项</p>
                        <ReactSortable
                            key={fieldName}
                            className={styles.selectBox}
                            list={selectedData}
                            group="selectedGroup"
                            animation={200}
                            delayOnTouchStart
                            delay={2}
                            setList={setSelectedData}
                            onMove={handleSortMove}
                            filter=".ignore"
                        >
                            {selectedData.map(item => (
                                <div
                                    key={item[fieldName]}
                                    className={`${styles.selectItem} ${
                                        item.isDisabled ? `${styles.disabled} ignore` : ''
                                    }`}
                                    data-disabled={`${item.isDisabled ? 'true' : 'false'}`}
                                >
                                    {item[fieldName]}{' '}
                                    {!item.isDisabled && <Icon type="close" onClick={() => handleRemove(item)} />}
                                </div>
                            ))}
                        </ReactSortable>
                    </div>
                    <div className={styles.unselectedWrapper}>
                        <p>未显示项</p>
                        <div className={styles.selectBox}>
                            {unselectedData.map(item => (
                                <div key={item[fieldName]}>
                                    {item[fieldName]} <Icon type="plus" onClick={() => handleAdd(item)} />
                                </div>
                            ))}
                        </div>
                    </div>
                </>
            ) : (
                <Result title="暂无数据" />
            )}
        </Modal>
    );
};

export default SortableModal;
